package server;

import java.io.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Arrays;
import java.util.Iterator;
import java.util.stream.Stream;

public class MessageBuffer {
    private final String HISTORY_PATH = "C:\\Users\\Student\\db-pr-1\\History.txt";
    private String[] messageArray;
    private int counter;

    public MessageBuffer() {
        counter = 0;
        messageArray = new String[300];
    }

    public void put(String message) {
        messageArray[counter] = message;
        counter++;
        if (counter > 10) {
            saveBufferedHistory();
        }
    }

    public String getHistory() {
        String[] buffer = Arrays.copyOf(messageArray, counter);
        StringBuilder result = new StringBuilder();
        try (BufferedReader in = new BufferedReader(new FileReader(HISTORY_PATH))) {
            Stream<String> stringStream = in.lines();
            Iterator<String> iterator = stringStream.iterator();
            while (iterator.hasNext()) {
                result.append(iterator.next()).append("\n");
            }
        } catch (IOException e) {
            System.err.println("Cannot save History");
        }
        for (String s : buffer) {
            result.append(s).append("\n");
        }
        return result.toString();
    }

    private void saveBufferedHistory() {
        File file = new File(HISTORY_PATH);
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                System.err.println("Cannot create history file");
            }
        }
        try (BufferedWriter out = new BufferedWriter(new FileWriter(HISTORY_PATH))) {
            for (int i = 0; i < counter; i++) {
                out.write(messageArray[i]);
            }
        } catch (IOException e) {
            System.err.println("Cannot save History");
        }
        counter = 0;
    }
}